package l1j.server.server.model.Instance;

import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import l1j.opqlo.Server.L1World.L1World;
import l1j.opqlo.Server.L1World.WorldClan;
import l1j.opqlo.Server.L1World.WorldWar;
import l1j.server.server.datatables.DoorSpawnTable;
import l1j.server.server.datatables.lock.ClanReading;
import l1j.server.server.model.L1CastleLocation;
import l1j.server.server.model.L1Clan;
import l1j.server.server.model.L1Object;
import l1j.server.server.model.L1Teleport;
import l1j.server.server.model.L1War;
import l1j.server.server.model.L1WarSpawn;
import l1j.server.server.serverpackets.S_CastleMaster;
import l1j.server.server.serverpackets.S_PacketBoxWar;
import l1j.server.server.serverpackets.S_RemoveObject;
import l1j.server.server.serverpackets.S_ServerMessage;
import l1j.server.server.templates.L1Npc;

public class L1CrownInstance extends L1NpcInstance {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final Logger _log = Logger.getLogger(L1CrownInstance.class.getName());



	public L1CrownInstance(L1Npc template) {
		super(template);
	}

	@Override
	public void onAction(L1PcInstance player) {
		try {
			boolean in_war = false;

			// 例外狀況:不具備血盟
			if (player.getClanid() == 0) { 
				return;
			}
			// 人物所屬血盟名稱
			final String playerClanName = player.getClanname();
			// 該血盟數據
			final L1Clan clan = WorldClan.get().getClan(playerClanName);
			// 例外狀況:不具備血盟
			if (clan == null) {
				return;
			}
			// 例外狀況:人物死亡
			if (player.isDead()) {
				return;
			}
			// 例外狀況:人物死亡
			if (player.getCurrentHp() <= 0) {
				return;
			}
			// 鬼魂模式
			if (player.isGhost()) {
				return;
			}
			// 傳送中
			if (player.isTeleport()) {
				return;
			}
			// 例外狀況:不是王族
			if (!player.isCrown()) { 
				return;
			}
			// 例外狀況:有變身(人物外型不是公主或王子)
			if (player.getTempCharGfx() != 0 &&
					player.getTempCharGfx() != 1) {
				return;
			}
			// 例外狀況:非盟主
			if (player.getId() != clan.getLeaderId()) {
				return;
			}
			// 例外狀況:距離過遠
			if (!this.checkRange(player)) { 
				return;
			}
			// 例外狀況:其他城堡城主
			if (clan.getCastleId() != 0) {
				// 474:你已經擁有城堡，無法再擁有其他城堡。
				player.sendPackets(new S_ServerMessage(474));
				return;
			}

			// 王冠座標取回城堡編號
			final int castle_id = L1CastleLocation.getCastleId(this.getX(), this.getY(), this.getMapId());

			// 布告しているかチェック。但し、城主が居ない場合は布告不要
			boolean existDefenseClan = false;
			final L1Clan defence_clan = L1CastleLocation.mapCastle().get(new Integer(castle_id));

			if (defence_clan != null) {
				existDefenseClan = true;
			}
			//		for (L1Clan defClan : L1World.getInstance().getAllClans()) {
			//			if (castle_id == defClan.getCastleId()) {
			//				// 元の城主クラン
			//				defence_clan = L1World.getInstance().getClan(defClan.getClanName());
			//				existDefenseClan = true;
			//				break;
			//			}
			//		}

			// 取回全部戰爭訊息
			final List<L1War> wars = WorldWar.get().getWarList(); // 全戦争リストを取得

			for (final L1War war : wars) {
				if (castle_id == war.get_castleId()) { // 今居る城の戦争
					in_war = war.checkClanInWar(playerClanName);
					break;
				}
			}
			if (existDefenseClan && in_war == false) { // 城主が居て、布告していない場合
				return;
			}
			// メッセージ表示
			for (L1War war : wars) {
				if (war.checkClanInWar(playerClanName) && existDefenseClan) {
					// 自クランが参加中で、城主が交代
					if (castle_id == war.get_castleId()) { // 今居る城の戦争
						war.winCastleWar(playerClanName);
					}else{
						war.ceaseWar(playerClanName , null);
					}
				}
			}

			// clan_dataのhascastleを更新し、キャラクターにクラウンを付ける
			/*	if (existDefenseClan && defence_clan != null) { // 元の城主クランが居る
			defence_clan.setCastleId(0);
			ClanReading.get().updateClan(defence_clan);
			L1PcInstance defence_clan_member[] = defence_clan.getOnlineClanMember();
			for (int m = 0; m < defence_clan_member.length; m++) {
				if (defence_clan_member[m].getId() == defence_clan.getLeaderId()) { // 元の城主クランの君主
					defence_clan_member[m].sendPackets(new S_CastleMaster(0,defence_clan_member[m].getId()));
					defence_clan_member[m].broadcastPacket(new S_CastleMaster(0, defence_clan_member[m].getId()));
					break;
				}
			}
		}*/
			// 原城盟不為空 消除相關城堡數據
			if (existDefenseClan && (defence_clan != null)) { // 原城主不為空
				defence_clan.setCastleId(0);
				ClanReading.get().updateClan(defence_clan);

				// 原城主王冠消除
				if (L1CastleLocation.mapCastle().get(new Integer(castle_id)) != null) {
					L1CastleLocation.removeCastle(new Integer(castle_id));
				}

				L1World.getInstance().broadcastPacketToAll(new S_CastleMaster(0, defence_clan.getLeaderId()));
			}

			clan.setCastleId(castle_id);
			ClanReading.get().updateClan(clan);

			// 新城主王冠顯示
			if (L1CastleLocation.mapCastle().get(new Integer(castle_id)) == null) {
				L1CastleLocation.putCastle(castle_id, clan);
			}
			if (castle_id == 2) {// 妖魔城主 暫時使用8顯示王冠
				L1World.getInstance().broadcastPacketToAll(new S_CastleMaster(8, player.getId()));

			} else {
				L1World.getInstance().broadcastPacketToAll(new S_CastleMaster(castle_id, player.getId()));
			}

			// 血盟以外成員強制移出
			int[] loc = new int[3];
			for (L1PcInstance pc : L1World.getInstance().getAllPlayers()) {
				if (pc.getClanid() != player.getClanid() && !pc.isGm()) {
					if (L1CastleLocation.checkInWarArea(castle_id, pc)) {
						// 戰爭旗幟範圍內
						loc = L1CastleLocation.getGetBackLoc(castle_id);
						int locx = loc[0];
						int locy = loc[1];
						short mapid = (short) loc[2];
						L1Teleport.teleport(pc, locx, locy, mapid, 5, true);
					}
				}
			}

			final L1PcInstance[] clanMember = clan.getOnlineClanMember();

			if (clanMember.length > 0) {
				for (final L1PcInstance pc : clanMember) {
					if (pc.getId() == clan.getLeaderId()) {
						// (642) 已掌握了城堡的主導權。
						pc.sendPackets(new S_PacketBoxWar(S_PacketBoxWar.MSG_WAR_INITIATIVE));
					}
					// (643) 已佔領城堡。
					pc.sendPackets(new S_PacketBoxWar(S_PacketBoxWar.MSG_WAR_OCCUPY));
				}
			}

			// 地面王冠物件刪除
			this.deleteMe();

			// 刪除損壞的守護塔
			for (L1Object l1object : L1World.getInstance().getObject()) {
				if (l1object instanceof L1TowerInstance) {
					final L1TowerInstance tower = (L1TowerInstance) l1object;
					if (L1CastleLocation.checkInWarArea(castle_id, tower)) {
						tower.deleteMe();
					}
				}
			}
			L1WarSpawn warspawn = new L1WarSpawn();
			warspawn.SpawnTower(castle_id);

			// 城門を元に戻す
			for (L1DoorInstance door : DoorSpawnTable.getInstance().getDoorList()) {
				if (L1CastleLocation.checkInWarArea(castle_id, door)) {
					door.repairGate();
				}
			}
		} catch (final Exception e) {
			_log.log(Level.SEVERE ,e.getLocalizedMessage(), e);
		}
	}

	@Override
	public void deleteMe() {
		_destroyed = true;
		if (getInventory() != null) {
			getInventory().clearItems();
		}
		this.allTargetClear();
		this._master = null;
		L1World.getInstance().removeVisibleObject(this);
		L1World.getInstance().removeObject(this);
		for (L1PcInstance pc : L1World.getInstance().getRecognizePlayer(this)) {
			pc.removeKnownObject(this);
			pc.sendPackets(new S_RemoveObject(this));
		}
		removeAllKnownObjects();
	}

	private boolean checkRange(L1PcInstance pc) {
		return (this.getX() - 1 <= pc.getX() && pc.getX() <= this.getX() + 1
				&& this.getY() - 1 <= pc.getY() && pc.getY() <= this.getY() + 1);
	}
}
